<template>
  <view class="share-container" v-if="canload">
    <!-- 商品海报图 -->
    <view class="poster-section">
      <view class="goods-card">
        <image
          @tap="previewImage"
          :data-url="sharePoster"
          class="goods-image"
          :src="sharePoster"
          mode="aspectFit"
        >
        </image>
      </view>
    </view>

    <!-- 底部固定内容 -->
    <view class="bottom-section">
      <!-- 商品图片列表 -->
      <view class="image-grid">
        <view class="grid-title">
          <text
            >同时下载多张商品图片 (<text :style="{ color: t('color1') }">{{
              selectedImages.length
            }}</text
            >/{{ goodsImages.length }})</text
          >
          <text class="select-all-btn" @click="toggleSelectAll">{{
            isSelectAll ? "取消全选" : "全选"
          }}</text>
        </view>
        <scroll-view class="grid-container" scroll-x>
          <view
            class="image-item"
            v-for="(item, index) in goodsImages"
            :key="index"
            @click="toggleSelect(index)"
          >
            <image :src="item" mode="aspectFill"></image>
            <view class="select-mask2"> </view>
            <view
              class="select-mask"
              :class="{ selected: selectedImages.includes(index) }"
            >
              <view
                class="select-circle"
                :style="{ backgroundColor: t('color1') }"
              >
                <!-- <text v-if="selectedImages.includes(index)">✓</text> -->
                <image
                  v-if="selectedImages.includes(index)"
                  src="@/static/img/checkd.png"
                  mode="aspectFit"
                ></image>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 下载海报按钮 :disabled="selectedImages.length === 0"-->
      <button
        class="download-btn"
        :style="{ backgroundColor: t('color1') }"
        @click.stop.prevent="save"
      >
        <!-- 下载海报<text v-if="selectedImages.length > 0">({{ selectedImages.length }})</text> -->
        <image
          style="
            width: 30rpx;
            height: 30rpx;
            margin-right: 10rpx;
            margin-bottom: -5rpx;
          "
          src="@/pagesExt/static/images/down.png"
          mode="aspectFit"
        >
        </image>
        下载海报
      </button>

      <!-- 分享方式 -->
      <view class="share-methods">
        <text class="divider-text">——————————————————</text>
        <text class="divider-text">或</text>
        <view class="methods-list">
          <!-- <view class="method-item">
            <button
              class="method-item"
              plain
              style="border: none; box-shadow: none"
              @click="dialogToggle"
            >
              <image src="@/pagesExt/static/images/pyq.png" mode="aspectFit">
              </image>
              <text style="transform: translateX(-10rpx)"
                ><text style="opacity: 0">占</text>朋友圈</text
              >
            </button>
          </view> -->
          <view class="method-item">
            <button
              class="method-item"
              plain
              open-type="share"
              @click="share"
              style="border: none; box-shadow: none"
            >
              <image src="@/static/img/weixin.png" mode="aspectFit"></image>
              <text>分享好友</text>
            </button>
          </view>
          <view class="method-item">
            <button
              class="method-item"
              plain
              style="border: none; box-shadow: none"
              @click="copyLink"
            >
              <image
                src="@/pagesExt/static/images/link.png"
                mode="aspectFit"
              ></image>
              <text>复制链接</text>
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 提示窗示例 -->
    <uni-popup ref="alertDialog" type="dialog">
      <view class="tipcontent">
        <view class="tiptitle">分享到朋友圈</view>
        <image :src="tipimg" mode="aspectFit"></image>
        <button
          class="tipbtn"
          @tap="closedia"
          :style="{ backgroundColor: t('color1') }"
        >
          我知道了
        </button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
var app = getApp();
export default {
  data() {
    return {
      canload: false,
      id: "",
      ptype: "",
      share_title: "",
      share_path: "",
      share_imageUrl: "",
      sharePoster: "",
      selectedImages: [],
      selectedImages2: [],
      goodsImages: [],
      isSelectAll: false, // 新增：追踪全选状态
      product: {},
      tipimg:
        "https://hedashepin.oss-cn-guangzhou.aliyuncs.com/upload/3/20250317/6c8755ec7b6473ba8c735b4bfb95773b.png",
      getposterUrl: "Shop/getposter", //海报请求接口
      getproductUrl: "Shop/product", //商品详情接口
      shareUrl: "/pages/shop/product", //分享链接接口
      pmid: 0, //分享人的id
    };
  },
  onLoad(options) {
    console.log(options);
    if (options.from == "shareTimeline") {
      app.goto(
        options.params +
          "?id=" +
          options.gid +
          "&ptype=" +
          options.ptype +
          "&pmid=" +
          options.pmid,
        "reLaunch"
      );
      return;
    }
    this.pmid = app.globalData.mid;
    this.canload = true;
    this.id = options.id;
    this.ptype = options.ptype;
    this.checkUrl(options.ptype);
    this.getdata();
  },

  methods: {
    checkUrl(ptype) {
      switch (ptype) {
        case "seckill":
          // this.getposterUrl = 'Seckill/getposter'
          this.getproductUrl = "Seckill/product";
          // this.shareUrl = '/pagesExt/seckill/product'
          break;
        case "groupby":
          // this.getposterUrl = 'Groupby/getposter'
          this.getproductUrl = "Groupby/product";
          // this.shareUrl = '/pagesExt/seckill/product'
          break;
        default:
          // this.getposterUrl = ' '
          this.getproductUrl = "Shop/product";
          this.shareUrl = "/pages/shop/product";
          break;
      }
    },
    getdata() {
      let that = this;
      app.showLoading("生成海报中");
      app.post(
        that.getposterUrl,
        {
          proid: that.id,
          type: that.ptype,
        },
        function (data) {
          app.showLoading(false);
          if (data.status == 0) {
            app.alert(data.msg);
          } else {
            that.sharePoster = data.poster;
          }
        }
      );
      app.get(
        that.getproductUrl,
        {
          id: that.id,
        },
        function (res) {
          if (res.status == 0) {
            app.alert(res.msg);
            return;
          }
          that.product = res.product;
          that.share_title = res.product.name;
          that.share_path =
            "/pages/shop/product?id=" +
            that.id +
            "&ptype=" +
            that.ptype +
            "&pmid=" +
            that.pmid;
          that.goodsImages = res.product.pics;
          that.share_imageUrl = res.product.pics[0];
        }
      );
    },

    // toggleSelect(index) {
    //   const selectedIndex = this.selectedImages.indexOf(index);
    //   if (selectedIndex > -1) {
    //     this.selectedImages.splice(selectedIndex, 1);
    //   } else {
    //     this.selectedImages.push(index);
    //   }
    //   // 更新全选状态
    //   this.isSelectAll = this.selectedImages.length === this.goodsImages.length;
    // },
    toggleSelectAll() {
      if (this.isSelectAll) {
        // 当前是全选状态，则取消全选
        this.selectedImages = [];
        this.selectedImages2 = [];
      } else {
        this.selectedImages = [];
        this.selectedImages2 = [];
        // 当前未全选，则全选
        this.selectedImages = this.goodsImages.map((_, index) => index);
        this.goodsImages.forEach((item) => {
          this.selectedImages2.push(item);
        });
      }
      this.isSelectAll = !this.isSelectAll;
    },
    checkUrl(ptype) {
      switch (ptype) {
        case "seckill":
          // this.getposterUrl = 'Seckill/getposter'
          this.getproductUrl = "Seckill/product";
          // this.shareUrl = '/pagesExt/seckill/product'
          break;
        case "groupby":
          // this.getposterUrl = 'Groupby/getposter'
          this.getproductUrl = "Groupby/product";
          // this.shareUrl = '/pagesExt/seckill/product'
          break;
        default:
          // this.getposterUrl = ' '
          this.getproductUrl = "Shop/product";
          this.shareUrl = "/pages/shop/product";
          break;
      }
    },
    getdata() {
      let that = this;
      app.showLoading("生成海报中");
      app.post(
        that.getposterUrl,
        {
          proid: that.id,
          type: that.ptype,
        },
        function (data) {
          app.showLoading(false);
          if (data.status == 0) {
            app.alert(data.msg);
          } else {
            that.sharePoster = data.poster;
          }
        }
      );
      app.get(
        that.getproductUrl,
        {
          id: that.id,
        },
        function (res) {
          if (res.status == 0) {
            app.alert(res.msg);
            return;
          }
          that.product = res.product;
          that.share_title = res.product.name;
          that.share_path =
            "/pages/shop/product?id=" +
            that.id +
            "&ptype=" +
            that.ptype +
            "&pmid=" +
            that.pmid;
          that.goodsImages = res.product.pics;
          that.share_imageUrl = res.product.pics[0];
        }
      );
    },

    toggleSelect(index) {
      const position = this.selectedImages.indexOf(index);
      if (position === -1) {
        // if (this.selectedImages.length < 7) {
        this.selectedImages.push(index);
        this.selectedImages2.push(this.goodsImages[index]);
        // }
      } else {
        this.selectedImages.splice(position, 1);
        this.selectedImages2.splice(position, 1);
      }
    },
    //保存
    save(e) {
      var _this = this;
      let dimg = [];
      dimg.push(_this.sharePoster);
      _this.selectedImages2.forEach((item) => {
        dimg.push(item);
      });

      dimg.forEach((i) => {
        // var src = this.sharePoster;
        let src = i;
        //#ifdef MP-WEIXIN
        //提前向用户发起授权请求
        uni.authorize({
          scope: "scope.writePhotosAlbum",
          success() {
            console.log("dp-previewImage:允许储存=>", src);
            _this.downloadImg(src);
          },
        });
        //#endif

        //#ifdef APP-PLUS
        _this.downloadImg(src);
        //#endif

        //#ifdef H5
        //非同源图片将直接打开
        var abtn = document.createElement("a");
        abtn.href = src;
        abtn.download = "";
        abtn.target = "_blank";
        abtn.click();
        //#endif
      });
    },

    //下载并保存文件
    downloadImg(src) {
      //下载图片文件
      uni.showLoading({
        title: "大图提取中",
      });
      uni.downloadFile({
        url: src,
        success: function (res) {
          console.log("dp-previewImage:下载成功=>", src);
          uni.hideLoading();
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              uni.showToast({
                title: "已保存至相册",
                duration: 1000,
              });
            },
          });
        },
        fail: function () {
          uni.hideLoading();
          uni.showToast({
            title: "图片下载失败",
            icon: "none",
            duration: 1000,
          });
        },
      });
    },

    dialogToggle() {
      this.share();
      this.$refs.alertDialog.open();
    },

    closedia() {
      this.$refs.alertDialog.close();
    },

    share() {
      let that = this;
      uni.share({
        title: that.share_title,
        path: that.share_path,
        imageUrl: that.share_imageUrl,
      });
    },

    copyLink: function () {
      var that = this;
      app.showLoading();
      app.post(
        "Shop/getwxScheme",
        {
          proid: that.id,
          type: that.ptype,
        },
        function (data) {
          app.showLoading(false);
          if (data.status == 0) {
            app.alert(data.msg);
          } else {
            // that.showScheme = true;
            // that.schemeurl = data.openlink
            uni.setClipboardData({
              data: data.openlink,
              success: () => {
                uni.showToast({
                  title: "链接已复制",
                  icon: "success",
                  duration: 1000,
                });
              },
            });
          }
        }
      );
    },
  },
  onShareAppMessage() {
    return {
      title: this.share_title,
      path: this.share_path,
      imageUrl: this.share_imageUrl,
    };
  },

  onShareTimeline(res) {
    return {
      title: this.share_title,
      imageUrl: this.share_imageUrl,
      // path: this.share_path,分享到朋友圈不能设置路径只能分享当前页
      query:
        "from=shareTimeline&params=" +
        this.shareUrl +
        "&gid=" +
        this.id +
        "&ptype=" +
        this.ptype +
        "&pmid=" +
        this.pmid, //页面打开的传参
    };
  },
};
</script>

<style lang="scss" scoped>
.share-container {
  // display: flex;
  // flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  overflow: hidden;
}

.poster-section {
  flex: 1;
  // padding: 20rpx;
  // overflow-y: auto;
  height: 60vh;
}

.bottom-section {
  background: #fff;
  padding: 20rpx;
  padding-top: 0;
  // height: 100%;
  height: 40vh;
  // border-top-left-radius: 20rpx;
  // border-top-right-radius: 20rpx;
}

.goods-card {
  background-color: #fff;
  // border-radius: 16rpx;
  padding: 20rpx;
  height: 100%;
  position: relative;

  .goods-image {
    width: 100%;
    height: 100%;
    border-radius: 12rpx;
  }
}

.image-grid {
  .grid-title {
    font-size: 26rpx;
    color: #333;
    margin-bottom: 20rpx;
  }

  .grid-container {
    white-space: nowrap;

    .image-item {
      display: inline-block;
      position: relative;
      width: 180rpx;
      height: 180rpx;
      margin-right: 20rpx;
      border-radius: 12rpx;
      overflow: hidden;

      &:last-child {
        margin-right: 0;
      }

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .select-mask {
        position: absolute;
        top: 10rpx;
        // left: 0;
        right: 10rpx;
        // bottom: 0;
        // background: rgba(0, 0, 0, 0.3);
        background: #fff;
        border-radius: 50%;
        // border: 2rpx solid #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;

        &.selected {
          opacity: 1;
          // background: rgba(0, 0, 0, 0.3);
        }

        .select-circle {
          width: 50rpx;
          height: 50rpx;
          border-radius: 50%;
          // border: 2rpx solid #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          background: #00b578;
        }
      }

      .select-mask2 {
        position: absolute;
        top: 10rpx;
        right: 10rpx;
        width: 50rpx;
        height: 50rpx;
        background: #fff;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

.download-btn {
  background-color: #00b578;
  color: #fff;
  border-radius: 40rpx;
  font-size: 32rpx;
  margin: 30rpx auto;
  width: 80%;

  &:disabled {
    background-color: #ccc;
  }
}

.share-methods {
  position: relative;
  padding: 40rpx 0;

  .divider-text {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    background-color: #fff;
    padding: 0 20rpx;
    color: #9f9f9f;
    font-size: 28rpx;
  }

  .methods-list {
    display: flex;
    justify-content: space-around;
    padding-top: 20rpx;

    .method-item {
      text-align: center;
      display: flex;
      flex-direction: column;
      align-items: center;

      image {
        width: 76rpx;
        height: 76rpx;
      }

      text {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.tipcontent {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 20rpx 0;

  .tiptitle {
    margin-top: 20rpx;
    text-align: center;
    font-size: 40rpx;
    font-weight: bold;
  }

  .tipbtn {
    font-size: 30rpx;
    border-radius: 50rpx;
    width: 65%;
    color: #fff;
    padding: 8rpx 0;
    margin-bottom: 20rpx;
  }
}
.grid-title {
  display: flex;
  justify-content: space-between; // 使标题和全选按钮分别在两侧
  align-items: center;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  .select-all-btn {
    font-size: 26rpx;
    color: #007aff; // 您可以根据主题色修改
    cursor: pointer;
  }
}

.grid-container {
  white-space: nowrap;

  .image-item {
    display: inline-block;
    position: relative;
    width: 180rpx;
    height: 180rpx;
    margin-right: 20rpx;
    border-radius: 12rpx;
    overflow: hidden;

    &:last-child {
      margin-right: 0;
    }

    image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .select-mask {
      position: absolute;
      top: 10rpx;
      // left: 0;
      right: 10rpx;
      // bottom: 0;
      // background: rgba(0, 0, 0, 0.3);
      background: #fff;
      border-radius: 50%;
      // border: 2rpx solid #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;

      &.selected {
        opacity: 1;
        // background: rgba(0, 0, 0, 0.3);
      }

      .select-circle {
        width: 50rpx;
        height: 50rpx;
        border-radius: 50%;
        // border: 2rpx solid #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        background: #00b578;
      }
    }

    .select-mask2 {
      position: absolute;
      top: 10rpx;
      right: 10rpx;
      width: 50rpx;
      height: 50rpx;
      background: #fff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
